package com.campus.schedule.timer;

import com.campus.schedule.entity.Order;
import com.campus.schedule.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单自动拒单服务
 */
@Service
@Slf4j
public class OrderAutoRejectService {

    @Autowired
    private OrderService orderService;
    
    @Resource
    private KafkaTemplate<String, String> kafkaTemplate;
    
    @Resource
    private ObjectMapper objectMapper;
    
    private static final String AUTO_REJECT_TOPIC = "order_auto_reject";
    private static final int TIMEOUT_MINUTES = 10;

    /**
     * 自动拒单定时任务
     * 每分钟执行一次，查询待接单且支付时间超过10分钟的订单
     */
    @Scheduled(fixedDelay = 60000) // 每分钟执行一次
    public void autoRejectOrders() {
        try {
            log.info("开始执行自动拒单定时任务");
            
            // 计算10分钟前的时间
            LocalDateTime timeoutTime = LocalDateTime.now().minusMinutes(TIMEOUT_MINUTES);
            
            // 查询需要自动拒单的订单
            List<Order> ordersToReject = orderService.findOrdersToAutoReject(timeoutTime);
            
            if (ordersToReject.isEmpty()) {
                log.info("没有需要自动拒单的订单");
                return;
            }
            
            log.info("发现 {} 个需要自动拒单的订单", ordersToReject.size());
            
            // 循环遍历订单，发送Kafka消息
            for (Order order : ordersToReject) {
                // 发送Kafka消息通知商户端进行拒单处理
                Map<String, Object> message = new HashMap<>();
                message.put("orderId", order.getId());
                message.put("operatorType", 3); // 3表示系统操作
                
                try {
                    String messageJson = objectMapper.writeValueAsString(message);
                    kafkaTemplate.send(AUTO_REJECT_TOPIC, messageJson);
                    log.info("已发送自动拒单消息，订单ID: {}", order.getId());
                } catch (Exception e) {
                    log.error("发送自动拒单消息失败，订单ID: {}", order.getId(), e);
                }
            }
            
            log.info("自动拒单定时任务执行完成，共处理 {} 个订单", ordersToReject.size());
        } catch (Exception e) {
            log.error("自动拒单定时任务执行异常", e);
        }
    }
}